package com.antfin.exam.bonus.dao;

import com.antfin.exam.bonus.model.ReduceScoreEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

@Component
public class BonusScoreDao {

    @Autowired
    protected JdbcTemplate jdbcTemplate;

    /**
     * 从数据库中读取记录分数
     * @param bonusScoreId
     * @return
     */
    public int queryRemainScore(String bonusScoreId){
        String sql = "select REMAIN_SCORE from BONUS_SCORE where BONUS_SCORE_ID=?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt(1);
            }
        },new Object[]{bonusScoreId});

    }

    /**
     * 把剩余分数更新到数据表中
     * @param bonusScoreId
     * @param remainScore
     * @return
     */
    public int updateRemainScore(String bonusScoreId,int remainScore){
        String sql = "update BONUS_SCORE set REMAIN_SCORE=? where BONUS_SCORE_ID=?";
        return jdbcTemplate.update(sql,new Object[]{remainScore,bonusScoreId});
    }

    /**
     * 数据表行级锁，防止记录被脏读
     * @param bonusScoreId
     */
    public void lockBondScore(String bonusScoreId){
        String sql = "update BONUS_SCORE set REMAIN_SCORE=REMAIN_SCORE where BONUS_SCORE_ID=?";
        jdbcTemplate.update(sql,new Object[]{bonusScoreId});
    }

    /**
     * 写扣减日志
     * @param entity
     */
    public void insertBonusScoreLog(ReduceScoreEntity entity){
        String sql = "INSERT INTO BONUS_SCORE_LOG(BONUS_SCORE_ID,USER_ID,REDUCE_SCORE,REMAIN_SCORE,CREATED_TIME) VALUE (?,?,?,?)";
        jdbcTemplate.update(sql,new Object[]{
                entity.getBonusScoreId(),
                entity.getUserId(),
                entity.getReduceScore(),
                entity.getRemainScore(),
                new Date()
        });

    }
}
